package com.unlcn.ils.wms.backend.service.bigscreen.impl;

import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.HttpRequestUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.unlcn.ils.wms.backend.bo.biBO.BiFrontShipmentBO;
import com.unlcn.ils.wms.backend.dto.bigscreenDTO.ShipmentDataDTO;
import com.unlcn.ils.wms.backend.enums.TmsUrlEnum;
import com.unlcn.ils.wms.backend.enums.TmsUrlTypeEnum;
import com.unlcn.ils.wms.backend.service.bigscreen.FrontShipmentService;
import com.unlcn.ils.wms.backend.util.TimeUtil;
import com.unlcn.ils.wms.base.mapper.bigscreen.BiFrontShipmentMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.BiFrontShipmentExtMapper;
import com.unlcn.ils.wms.base.mapper.sys.TmsCallHistoryMapper;
import com.unlcn.ils.wms.base.model.bigscreen.BiFrontShipment;
import com.unlcn.ils.wms.base.model.sys.TmsCallHistory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 前端发运模式推移图service
 */
@Service
public class FrontShipmentServiceImpl implements FrontShipmentService {

    @Autowired
    private BiFrontShipmentExtMapper biFrontShipmentExtMapper;

    @Autowired
    private BiFrontShipmentMapper biFrontShipmentMapper;

    @Autowired
    private TmsCallHistoryMapper tmsCallHistoryMapper;

    @Value("${tms.pickup.host.url}")
    private String propertyUrl;

    @Value("${tms.pickup.host.timeout}")
    private String propertyTime;

    @Value("${tms.encode.key}")
    private String propertyKey;

    private Logger LOGGER = LoggerFactory.getLogger(FrontShipmentServiceImpl.class);

    @Override
    public List<ShipmentDataDTO> shipmentChartCount() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        // 查询五天内最新的提车推移图统计数据
        List<BiFrontShipment> biFrontShipmentList = biFrontShipmentExtMapper.shipmentChartCount();

        ShipmentDataDTO shipmentDataDTO1 = new ShipmentDataDTO();
        ShipmentDataDTO shipmentDataDTO2 = new ShipmentDataDTO();
        ShipmentDataDTO shipmentDataDTO3 = new ShipmentDataDTO();
        ShipmentDataDTO shipmentDataDTO4 = new ShipmentDataDTO();

        shipmentDataDTO1.setName("入库");
        shipmentDataDTO2.setName("发运");
        shipmentDataDTO3.setName("库存");
        shipmentDataDTO4.setName("发运及时率");

        Integer[] count1 = new Integer[5];
        Integer[] count2 = new Integer[5];
        Integer[] count3 = new Integer[5];
        Float[] rate4 = new Float[5];

        String[] dates = TimeUtil.getBeforeDates1(5);
        for (int i=0; dates.length>i; i++) {
            String date = dates[i];
            for (int num=0; biFrontShipmentList.size()>num; num++) {
                BiFrontShipment biFrontShipment= biFrontShipmentList.get(num);
                if (format.format(biFrontShipment.getStatisticsTime()).contains(date)) {
                    count1[i] = biFrontShipment.getInBoundCount();
                    count2[i] = biFrontShipment.getShipmentCount();
                    count3[i] = biFrontShipment.getInventoryCount();
                    rate4[i] = biFrontShipment.getShipmentRate();
                    break;
                }
            }
        }
        for (Integer num=0; count1.length>num; num++) {
            Integer count = count1[num];
            if (count == null)
                count1[num] = 0;
        }
        for (Integer num=0; count2.length>num; num++) {
            Integer count = count2[num];
            if (count == null)
                count2[num] = 0;
        }
        for (Integer num=0; count3.length>num; num++) {
            Integer count = count3[num];
            if (count == null)
                count3[num] = 0;
        }
        for (Integer num=0; rate4.length>num; num++) {
            Float rate = rate4[num];
            if (rate == null)
                rate4[num] = new Float(0.0);
        }

        shipmentDataDTO1.setData(count1);
        shipmentDataDTO2.setData(count2);
        shipmentDataDTO3.setData(count3);
        shipmentDataDTO4.setRate(rate4);

        shipmentDataDTO1.setDate(TimeUtil.getBeforeDates2(5));
        shipmentDataDTO2.setDate(TimeUtil.getBeforeDates2(5));
        shipmentDataDTO3.setDate(TimeUtil.getBeforeDates2(5));
        shipmentDataDTO4.setDate(TimeUtil.getBeforeDates2(5));

        List<ShipmentDataDTO> pickDataDTOList = new ArrayList<ShipmentDataDTO>();
        pickDataDTOList.add(shipmentDataDTO1);
        pickDataDTOList.add(shipmentDataDTO2);
        pickDataDTOList.add(shipmentDataDTO3);
        pickDataDTOList.add(shipmentDataDTO4);

        return pickDataDTOList;
    }

    @Override
    public void addFrontShipmentData(){

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        String dateStr = format.format(calendar.getTime());

        String strUrl=propertyUrl + TmsUrlEnum.BI_FRONT_SHIPMENT.getText();
        Integer time = Integer.parseInt(propertyTime);
        String encode_key = propertyKey;
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("encode-key", encode_key);

        map.put("date", dateStr);

        String result = null;

        TmsCallHistory tmsCallHistory=new TmsCallHistory();


        try {

            tmsCallHistory.setTmsUrl(strUrl);
            tmsCallHistory.setTmsUrlType(TmsUrlTypeEnum.BI_FRONT_SHIPMENT.getValue());
            tmsCallHistory.setCallStartTime(new Date());
            tmsCallHistory.setParameters(dateStr);
            tmsCallHistory.setPullOrPush(0);

            result = HttpRequestUtil.sendHttpPost(strUrl, headerMap, map, time);

        } catch (Exception e) {
            LOGGER.error("FrontShipmentServiceImpl.addFrontShipmentData error : ", e);
            throw new BusinessException("访问tms接口失败");
        }

        try{
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                String msg = jsonObject.getString("message");
                String records = jsonObject.getString("records");
                Boolean success = jsonObject.getBoolean("success");

                tmsCallHistory.setCallEndTime(new Date());
                tmsCallHistory.setMessage(msg);
                tmsCallHistory.setResultContent(result);


                if (!success) {
                    LOGGER.error("FrontShipmentServiceImpl callTms error msg: {}", msg);
                    tmsCallHistory.setResultCount(0);
                    tmsCallHistory.setSuccess(success);
                    tmsCallHistoryMapper.insertSelective(tmsCallHistory);
                }


                List<BiFrontShipmentBO> tmsBOList = JSONArray.parseArray(records, BiFrontShipmentBO.class);
                tmsCallHistory.setResultCount(tmsBOList.size());
                tmsCallHistory.setSuccess(success);
                tmsCallHistoryMapper.insertSelective(tmsCallHistory);

                SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmSS");

                Calendar calendar2 = Calendar.getInstance();
                calendar2.setTime(new Date());
                String dateStr2 = format2.format(calendar2.getTime());

                tmsBOList.forEach((BiFrontShipmentBO v) -> {
                    //新增
                    BiFrontShipment biFrontShipment = new BiFrontShipment();

                    biFrontShipment.setInBoundCount(Integer.parseInt(Strings.isNullOrEmpty(v.getIn_qty())?"0":v.getIn_qty()));
                    biFrontShipment.setInventoryCount(Integer.parseInt(Strings.isNullOrEmpty(v.getOncache_qty())?"0":v.getOncache_qty()));
                    biFrontShipment.setShipmentCount(Integer.parseInt(Strings.isNullOrEmpty(v.getOut_qty())?"0":v.getOut_qty()));
                    biFrontShipment.setShipmentRate(Float.parseFloat(Strings.isNullOrEmpty(v.getIntime_radio())?"0":v.getIntime_radio()));

                    biFrontShipment.setVersion(dateStr2);

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

                    try {
                        if(!Strings.isNullOrEmpty(v.getRpt_date())){
                            biFrontShipment.setStatisticsTime(sdf.parse(v.getRpt_date()));
                        }
                    } catch (ParseException e) {
                        LOGGER.error("FrontShipmentServiceImpl.addFrontShipmentData error : ", e);
                        throw new BusinessException("日期转换异常!");
                    }

                    biFrontShipmentMapper.insertSelective(biFrontShipment);

                });
            }

        }
        catch (Exception e) {
            LOGGER.error("FrontShipmentServiceImpl.addFrontShipmentData error : ", e);
            throw new BusinessException("保存失败");
        }
    }

}
